import json
from collections import defaultdict

DATASET_PATH = 'assets/database/main_database.json'
TARGET_USERNAME = "None"
GROUP_SIZE = 10  # 每组按键数量
MAX_GROUPS = 40  # 最大组数 (40组 × 10 = 400次按键)

def load_data(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def analyze_features(data, username):
    features = defaultdict(list)
    stats = {
        'user_entries': 0,
        'total_keystrokes': 0,
        'processed_keystrokes': 0,
        'negative_durations': 0,
        'interval_stats': {'total': 0, 'negative': 0, 'zero': 0},
        'group_speeds': []
    }

    print(f"\n正在分析用户: {username}")
    
    for entry in data:
        if entry['subject'] != username:
            continue
            
        stats['user_entries'] += 1
        keystrokes = entry['keystrokes']
        stats['total_keystrokes'] += len(keystrokes)

        # 只处理前400次按键
        remaining_keystrokes = MAX_GROUPS * GROUP_SIZE - stats['processed_keystrokes']
        if remaining_keystrokes <= 0:
            break
            
        current_keystrokes = keystrokes[:remaining_keystrokes]
        stats['processed_keystrokes'] += len(current_keystrokes)

        # 检测异常duration并记录原始数据
        for key_pos in range(len(current_keystrokes)):
            k = current_keystrokes[key_pos]
            duration = k['release_time'] - k['press_time']
            features['durations'].append(duration)
            if duration < 0:
                stats['negative_durations'] += 1
                print(f"异常duration：[用户第{stats['user_entries']}次击键] "
                      f"第{key_pos}键 | duration={duration:.6f}s")

        # 检测异常interval并记录原始数据
        for key_pos in range(1, len(current_keystrokes)):
            prev, curr = current_keystrokes[key_pos-1], current_keystrokes[key_pos]
            interval = curr['press_time'] - prev['release_time']
            
            stats['interval_stats']['total'] += 1
            features['intervals'].append(interval)  # 记录所有interval
            
            if interval < 0:
                stats['interval_stats']['negative'] += 1
                print(f"异常间隔：[用户第{stats['user_entries']}次击键] "
                      f"第{key_pos-1}-{key_pos}键 | 间隔={interval:.6f}s")
            elif interval == 0:
                stats['interval_stats']['zero'] += 1

        # 计算每组速度（包含异常数据）
        for i in range(0, len(current_keystrokes), GROUP_SIZE):
            group = current_keystrokes[i:i+GROUP_SIZE]
            if len(group) > 0:  # 允许任意长度的组
                total_time = group[-1]['release_time'] - group[0]['press_time']
                stats['group_speeds'].append(len(group) / total_time if total_time != 0 else float('inf'))

    # 打印结果
    print(f"\n用户统计:")
    print(f"已处理按键次数: {stats['processed_keystrokes']} (前{MAX_GROUPS}组)")
    print(f"负duration数量: {stats['negative_durations']}")
    print(f"间隔统计: {stats['interval_stats']}")

    return features, stats

def main():
    data = load_data(DATASET_PATH)
    features, stats = analyze_features(data, TARGET_USERNAME)
    print("\n分析完成")

if __name__ == "__main__":
    main()